import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

const state = {
  userInfo: {},
  musicId: '',
  musicUrl: '',
  musicDetail: {},
  playlist: [],
  isPlay: false
}
const actions = {
  async getMusic (context, musicId) {
    // 已经获取过的歌曲就直接播放
    if (context.state.musicId === musicId) {
      context.commit('changePlayState', true)
      return
    }
    console.log('不同歌曲')
    context.commit('changePlayState', false)
    const res1 = await axios.get(`/song/detail?ids=${musicId}`)
    // 在获取之前查看是否可以播放
    const check = await axios.get(`/check/music?id=${musicId}`)
    // 然后在获取url
    if (!check.data.success) return window.alert('check.data.message')
    const res2 = await axios.get(`/song/url?id=${musicId}`)
    // 因为是可以请求多个音乐url的，所以是数组
    context.commit('saveMusicId', musicId)
    context.commit('saveMusicDetail', res1.data.songs[0])
    context.commit('saveMusicUrl', res2.data.data[0].url)
    // 开始播放
    context.commit('changePlayState', true)
    // 将播放的音乐存入localStorage中
    const item = {
      musicId,
      musicDetail: {
        name: res1.data.songs[0].name,
        al: res1.data.songs[0].al,
        ar: res1.data.songs[0].ar
      },
      musicUrl: res2.data.data[0].url
    }
    context.dispatch('savePlaylist', item)
  },
  savePlaylist (context, item) {
    const playlist = JSON.parse(window.localStorage.getItem('playlist')) || []
    const index = playlist.findIndex(obj => {
      return obj.musicId === item.musicId
    })
    if (index !== -1) return
    playlist.push(item)
    window.localStorage.setItem('playlist', JSON.stringify(playlist))
    // 更新播放列表
    context.commit('updateMusicDetail')
  }
}
const mutations = {
  saveUserInfo (state, userInfo) {
    state.userInfo = userInfo
  },
  changePlayState (state, isPlay) {
    state.isPlay = isPlay
  },
  saveMusicId (state, musicId) {
    state.musicId = musicId
  },
  saveMusicUrl (state, musicUrl) {
    state.musicUrl = musicUrl
  },
  saveMusicDetail (state, musicDetail) {
    state.musicDetail = musicDetail
  },
  updateMusicDetail (state) {
    state.playlist = JSON.parse(window.localStorage.getItem('playlist')) || []
  }
}

export default new Vuex.Store({
  state,
  actions,
  mutations
})
